<script setup>
import { ref, onMounted, computed } from "vue";

// 页面参数
const props = defineProps({
  existingTags: {
    type: Array,
    default: () => [],
  },
});

// 数据状态
const tags = ref([]); // 当前标签列表
const inputText = ref(""); // 输入框内容
const maxTags = 10; // 最大标签数量

// 计算属性
const tagCount = computed(() => `${tags.value.length}/${maxTags}`);
const canAddTag = computed(() => tags.value.length < maxTags);
const isInputValid = computed(() => {
  const text = inputText.value.trim();
  return text.length > 0 && text.length <= 10 && !tags.value.includes(text);
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 添加标签
const addTag = () => {
  const text = inputText.value.trim();

  if (!text) {
    uni.showToast({
      title: "请输入标签内容",
      icon: "none",
    });
    return;
  }

  if (text.length > 10) {
    uni.showToast({
      title: "标签长度不能超过10个字符",
      icon: "none",
    });
    return;
  }

  if (tags.value.includes(text)) {
    uni.showToast({
      title: "标签已存在",
      icon: "none",
    });
    return;
  }

  if (tags.value.length >= maxTags) {
    uni.showToast({
      title: `最多只能添加${maxTags}个标签`,
      icon: "none",
    });
    return;
  }

  tags.value.push(text);
  inputText.value = "";
};

// 移除标签
const removeTag = (index) => {
  tags.value.splice(index, 1);
};

// 保存标签
const saveTags = () => {
  // 返回上一页并传递数据
  const pages = getCurrentPages();
  if (pages.length > 1) {
    const prevPage = pages[pages.length - 2];

    // 方法1：通过页面实例直接调用方法
    if (prevPage && prevPage.$vm && prevPage.$vm.updateFieldValue) {
      prevPage.$vm.updateFieldValue("jobTags", tags.value);
    }

    // 方法2：通过全局事件总线传递数据（备用方案）
    uni.$emit("updateJobTags", tags.value);
  }

  // 将标签数据存储到本地存储，供上一页面使用
  uni.setStorageSync("selectedTags", tags.value);

  uni.showToast({
    title: "保存成功",
    duration: 1500,
    success() {
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    },
  });
};

// 输入框回车事件
const onInputConfirm = () => {
  if (isInputValid.value && canAddTag.value) {
    addTag();
  }
};

// 页面加载
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options || {};

  // 从 URL 参数获取已有标签
  if (options.value) {
    const existingTagsString = decodeURIComponent(options.value);
    if (existingTagsString) {
      const existingTagsArray = existingTagsString
        .split(",")
        .filter((tag) => tag.trim());
      tags.value = [...existingTagsArray];
    }
  }

  // 从本地存储获取已有标签（备用方案）
  const existingTags = uni.getStorageSync("currentTags");
  if (existingTags && Array.isArray(existingTags) && tags.value.length === 0) {
    tags.value = [...existingTags];
  }
});
</script>

<template>
  <view class="position-tags-container">
    <!-- 页头 -->
    <view class="header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <image
            class="back-icon"
            src="/static/icons/candidate/pre_page.png"
          ></image>
        </view>
        <view class="header-title">职位标签</view>
        <view class="save-btn" @click="saveTags">
          <text class="save-text">保存</text>
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content">
      <!-- 标题和计数 -->
      <view class="title-section">
        <view class="title-row">
          <text class="main-title">职位标签</text>
          <text class="count-text">{{ tagCount }}</text>
        </view>
      </view>

      <!-- 提示信息 -->
      <view class="tip-section">
        <text class="tip-text"
          >合适的职位标签有利于被检索，更有助于突出显示给候选人</text
        >
      </view>

      <!-- 输入区域 -->
      <view class="input-section">
        <view class="input-wrapper">
          <input
            class="tag-input"
            v-model="inputText"
            placeholder="请输入职位标签"
            maxlength="10"
            @confirm="onInputConfirm"
          />
          <view
            class="add-btn"
            :class="{ disabled: !isInputValid || !canAddTag }"
            @click="addTag"
          >
            <text class="add-text">添加</text>
          </view>
        </view>
      </view>

      <!-- 标签列表 -->
      <view class="tags-section" v-if="tags.length > 0">
        <view class="tags-container">
          <view class="tag-item" v-for="(tag, index) in tags" :key="index">
            <text class="tag-text">{{ tag }}</text>
            <view class="remove-btn" @click="removeTag(index)">
              <text class="remove-text">×</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-section" v-else>
        <text class="empty-text">暂无标签，请添加职位标签</text>
      </view>
    </view>
  </view>
</template>

<style scoped lang="less">
.position-tags-container {
  background-color: #ffffff;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 页头样式 */
.header {
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 88rpx;
  padding-top: calc(20rpx + var(--status-bar-height, 0));
  position: relative;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333333;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.save-btn {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.save-text {
  font-size: 32rpx;
  color: #00bdb4;
  font-weight: 500;
}

/* 内容区域 */
.content {
  flex: 1;
  padding: 40rpx 30rpx;
}

/* 标题区域 */
.title-section {
  margin-bottom: 30rpx;
}

.title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.main-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

.count-text {
  font-size: 28rpx;
  color: #666666;
}

/* 提示区域 */
.tip-section {
  margin-bottom: 40rpx;
}

.tip-text {
  font-size: 28rpx;
  color: #999999;
  line-height: 40rpx;
}

/* 输入区域 */
.input-section {
  margin-bottom: 40rpx;
}

.input-wrapper {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.tag-input {
  flex: 1;
  height: 80rpx;
  padding: 0 20rpx;
  border: 2rpx solid #e9ecef;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333333;
  background-color: #ffffff;

  &::placeholder {
    color: #999999;
  }

  &:focus {
    border-color: #00bdb4;
  }
}

.add-btn {
  width: 120rpx;
  height: 80rpx;
  background-color: #00bdb4;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  &.disabled {
    background-color: #cccccc;
  }
}

.add-text {
  font-size: 28rpx;
  color: #ffffff;
  font-weight: 500;
}

/* 标签区域 */
.tags-section {
  flex: 1;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.tag-item {
  display: flex;
  align-items: center;
  background-color: #f8f9fa;
  border: 2rpx solid #e9ecef;
  border-radius: 40rpx;
  padding: 12rpx 20rpx;
  max-width: 300rpx;
}

.tag-text {
  font-size: 26rpx;
  color: #333333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.remove-btn {
  margin-left: 16rpx;
  width: 32rpx;
  height: 32rpx;
  background-color: #cccccc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-text {
  font-size: 24rpx;
  color: #ffffff;
  font-weight: 600;
  line-height: 1;
}

/* 空状态 */
.empty-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}
</style>